package com.heiketu.service.impl;

import com.heiketu.objs.Permission;
import com.heiketu.service.SpringMybatisUserDetailService;
import com.heiketu.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * UserDetailService实现
 * 1. spring security授权认证框架从UsernamePasswordAuthentication作为入口
 * 2. 使用DaoAuthenticationProvider交给UserDetailService来对登录用户进行授权
 */
@Service
public class SpringMybatisUserDetailServiceImpl implements SpringMybatisUserDetailService {

    @Autowired
    private TUserService tUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if(StringUtils.isEmpty(username)){
            return null; // 返回null，交由DtoAuthenticationProvider处理
        }
        com.heiketu.objs.User user = tUserService.findUserByUserName(username);
        if(Objects.isNull(user)){
            return null;
        }
        // 获得从数据库中查询到的相关用户信息，返回UserDetails对象给spring security的DtoAuthenticationProvider对象处理
        Set<Permission> permissions = user.getPermissions();
        List<String> strs = new ArrayList<>();
        permissions.forEach(x -> {
            String code = x.getCode();
            strs.add(code);
        });
        String[] str = new String[permissions.size()];
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities(strs.toArray(str)).build();
        return userDetails;
    }
}
